<template>
	<view>
		<view class="top-note-box">
			<view class="title">
				<text>说明：</text>
			</view>
			<view class="content">
				<text>能够进入此页面，说明之前已录入了与您的手机号关联的商铺数据，您的身份是该商铺的老板或负责人。</text>
			</view>
			<view class="content">
				<text>您只有进行了绑定操作后，才可以拥有对该店铺的设置和管理权限。绑定操作，只须点按“绑定”按钮并随后确认即可。</text>
			</view>
			<view class="content">
				<text>如果您的名下有多个商铺，须逐个进行绑定操作。</text>
			</view>
		</view>
		<unicloud-db ref="udb" collection="tian-mall-shops"
			field="ID,address,banner,shop_name,shop_desc,online,phone,logo_src,state" :where="where" page-data="replace"
			:orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
			v-slot:default="{data,pagination,loading,error,options}" :options="options" @load="loadData">

			<uni-table :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe>
				<uni-tr>
					<uni-th width="200rpx" align="center">操作</uni-th>
					<uni-th  align="center">商户名称</uni-th>
					<uni-th  align="center">地址电话</uni-th>
				</uni-tr>
				<uni-tr v-for="(item,index) in data" :key="index">
					<uni-td align="center">
						<button size="mini" type="primary" @click="boundAction(item)">绑定</button>
					</uni-td>
					<uni-td align="center">
						<view class="">
							<text>商户ID：{{item.ID}} </text>
						</view>
						<view class="">
							<text>{{item.shop_name.short_name}} </text>
						</view>
						<view class="">
							<text>{{item.shop_name.full_name}} </text>
						</view>
					</uni-td>
					<uni-td align="">
						<view class="">
							<text>
								{{item.address.address_number}}
							</text>
						</view>
						<view class="">
							<text>对外销售：{{item.phone.contact}}</text>
						</view>
						<view class="">
							<text>负责人：{{item.phone.head}}</text>
						</view>
						<view class="">
							<text>商务：{{item.phone.business}}</text>
						</view>
					</uni-td>

				</uni-tr>

			</uni-table>
			
		</unicloud-db>
		<view class="btn-box" >
			<button style="width: 30%;" type="default" @click="navBack">返回</button>
		</view>
		<uv-toast-wjf ref="uvToastWjf"></uv-toast-wjf>
		<uv-modal ref="uvModal" :title="uvModelParam.title" :content='uvModelParam.content' :align="uvModelParam.align"
			:confirmText="uvModelParam.confirmText" :cancelText="uvModelParam.cancelText"
			:showCancelButton="uvModelParam.showCancelButton"></uv-modal>

	</view>
</template>

<script>
	import {
		mapActions,
	} from 'vuex';
	import {
		// store as uniIdStore,
		mutations as uniIdMutations
	} from '@/uni_modules/uni-id-pages/common/store.js';
	import commMixinWjf from '@/common/mixin/common-mixin-wjf.js'
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'ID asc' // 排序字段
	// const dbSearchFields = ['shop_name.full_name','address.address_number','phone.head'] // 模糊搜索字段，支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 10
	const pageCurrent = 1
	export default {
		mixins: [commMixinWjf],
		data() {
			return {
				orderby: dbOrderBy,
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
				},
			}
		},
		computed: {
			userInfo() {
				return this.$store.state.user.userInfo
			},
			userMobile() {
				return this.userInfo.mobile ? this.userInfo.mobile : ''
			},
			where() {
				return `${new RegExp(this.userInfo.mobile)}.test(phone.head) && isBounded == false`
			}
		},
		methods: {
			...mapActions({
				getUserInfo: 'user/getUserInfo',
			}),
			// 成功的回调
			loadData(e) {
				// console.log(e);
			},
			navBack(){
				uni.navigateBack({
					delta: 1
				});
			},
			boundAction(item){
				this.$uvModal({
					content: '请再次确认',
					align: 'center',
					showCancelButton: true
				},()=>{
					this.confirmBound(item)
				})
			},
			confirmBound(item){
				console.log('item参数',item);
				// console.log(this.userInfo);
				uni.showLoading({
					title: '正在进行绑定操作，请稍候...',
					mask: false
				});
				let promise=[]
				promise.push(this.setUserShopInfo(item))
				promise.push(this.setShop(item))
				Promise.all(promise).then(res=>{
					uni.hideLoading()
					this.$uvToastWjf({
						message: "成功绑定！",
						type: 'success'
					})
					// uniIdMutations.setUserInfo(newUserInfo)
					this.getUserInfo()
					this.$refs.udb.loadData({
						clear:true
					})
					// this.navTimeBack();
					console.log(res);
				})
			},
			/**
			 * @param {Object} item shop数据
			 */
			async setUserShopInfo(item){
				let resUser=await db.collection('uni-id-users').doc(this.userInfo._id).field('role,shop_ID').get()
				let userRoles
				let userShopID
				if (resUser.result.data[0].role){
					userRoles=Array.from(new Set(["shop_owner",...resUser.result.data[0].role]))
				}else{
					userRoles=["shop_owner"]
				}
				if (resUser.result.data[0].shop_ID){
					userShopID=Array.from(new Set([item.ID,...resUser.result.data[0].shop_ID]))
				}else{
					userShopID=[item.ID]
				}
				
				return new Promise((resolve,reject)=>{
					db.collection('uni-id-users').doc(this.userInfo._id).update({
						role:userRoles,
						shop_ID:userShopID
					}).then(re=>{
						resolve(re)
					})
				})
			},
			setShop(item){
				return new Promise((resolve,reject)=>{
					db.collection('tian-mall-shops').doc(item._id).update({
						isBounded:true,
						shop_owner_id:[this.userInfo._id]
					}).then(r=>{
						resolve(r)
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f1f1f1;
	}
	.top-note-box{
		margin: 30rpx 20rpx;
		// background-color: #fff;
		padding: 20rpx;
		.title{
			font-size: 32rpx;
			color: #555;
			font-weight: 550;
		}
		.content{
			font-size: 28rpx;
			color: #777;
			margin: 10rpx 0;
		}
	}
	.btn-box{
		width: 100%;
		margin-top: 100rpx;
		display: flex;
	}
</style>